/*
 * ScrapLotAction.java
 *
 * Created on June 9, 2002, 12:54 AM
 */

package com.scalar.chiptrack.operations.process.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.engineering.dao.EngineeringDAO;
import com.scalar.chiptrack.operations.LotView;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.Mailer;

/**
 *
 * @author  Mallikarjun
 * @version 1.0
 */
public class LotSplitAction extends ChipTrackAction{
       private static final String ACTION_NAME = "/splitMergeLot.do";
       public ActionForward execute (ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
                                      throws Exception {

            DBTransaction dbt = null;
            boolean success = false;
            String lotaction = request.getParameter("lotaction");
            HashMap errors = new HashMap();
            HashMap info = new HashMap();
            String from = "";
            LotView lview = null;
            String splitLotNumber = null;
            int splitQuantity = 0;
            String lotNumber = null;
            int pull_quantity = 0;
            ArrayList splitList = null;

            // Added by veeru on 29th June 2004
            HttpSession hs = request.getSession();
            User user = (User)hs.getAttribute(SessionKeys.USER_KEY);
            if ( user == null )
            {
                hs.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
                return ( mapping.findForward ( "login" ) );
            }
            // End of Added by veeru

            if((lotaction != null) &&(lotaction.equalsIgnoreCase("LOT_SPLIT_SAVE"))){

            	//HttpSession hs = request.getSession(false);
            	lview = (LotView)hs.getAttribute(SessionKeys.LOT_VIEW);
                //lview = (LotView)request.getAttribute(SessionKeys.LOT_VIEW);
            	//User user = (User)hs.getAttribute(SessionKeys.USER_KEY);

                splitList = (ArrayList)hs.getAttribute(SessionKeys.SPLIT_LIST);
                //splitList = (ArrayList)request.getAttribute(SessionKeys.SPLIT_LIST);
                // Added by veeru on 25th June 2004
                if ( request.getParameter("splitQuantity") != null && !"".equals(request.getParameter("splitQuantity"))  )
                {
                    splitQuantity = Integer.parseInt(request.getParameter("splitQuantity"));
                }
                // End of added by veeru

                if(splitList.size() >= 2){
                        //System.out.println("This is check");
                        splitLotNumber = (String)splitList.get(1);
                }else{
                        splitLotNumber = lview.getLotNumber();
                }

            	//System.out.println("Lview object = "+ lview);
            	//System.out.println("Lot Number after View = "+ lview.getLotNumber());
            	//System.out.println("Lot ID after View = "+ lview.getLotID());
            	//System.out.println("Split Lot Number = "+ splitLotNumber);
            	//System.out.println("Split Lot Quantity = "+ request.getParameter("splitQuantity"));

                try{
	        	dbt = DBTransaction.getInstance();
	                dbt.begin();
	                int pullId = 0;
	                int alarmId = 0;

	                //operation 1
	                pullId = EngineeringDAO.splitLot(dbt,
	                				 lview,
	                				 splitLotNumber, splitQuantity);





	                //operation 3
	                //EngineeringDAO.updateAlarmID(dbt, "ENG_SCRAP", pullId, alarmId);

	                success = true;

	            }catch(Exception e){

	                e.printStackTrace();
	                throw new ScalarException("LotSplitAction failed", e);

	            }finally{
	                if(success){
	                    dbt.commit();
                        String mailTo = user.getEmail();
                        //String mailFrom = "chiptrac@scalarsoft.com";
                        String mailFrom = user.getEmail();
                        String subject = "Lot Split Information for lot : "+lview.getLotNumber();
                        String message = mailFormat(lview, splitLotNumber, splitQuantity);
                        info.put("Lot Split ", "Successfully Saved");
                        try
                        {
                            Mailer.send(mailFrom, mailTo, subject, message, Mailer.CONTENT_TYPE_HTML);
	                        info.put("E-mail ", "Mail has been sent");
                        }
                        catch( Exception e)
                        {
                            errors.put("E-mail ", "Could not sent Mail");
                        }

                    }else{
	                    dbt.rollback();
	                }

	                //hs.removeAttribute(SessionKeys.LOT_VIEW);
                        //hs.removeAttribute(SessionKeys.SPLIT_LIST);
	            }

	            if(!errors.isEmpty()) {
                    request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
                }
                if(!info.isEmpty()) {
                    request.setAttribute(SessionKeys.INFO_MESSAGES, info);
                }
                return mapping.findForward("engConfirm");

            }

            return mapping.findForward("success");
       }

       private String mailFormat(LotView lview, String splitLotNumber, int quantity) {

	        StringBuffer buf = new StringBuffer();

	        buf.append ("<table border='0'>\n");
	        buf.append ("<th colspan='4'><h2>Lot Split</h2></th>\n");
	        buf.append ("<tr><td width='20%'><b>Lot Number</b></td>\n");
	        buf.append ("<td width='40%'>" + lview.getLotNumber() + "</td>\n");
	        buf.append ("<td width='20%'><b>Product Name</b></td>\n");
	        buf.append ("<td width='20%'>" + lview.getPartNumber() + "</td>\n");
	        buf.append ("</tr><tr><td width='20%'><b>Current Process</b></td>\n");
	        buf.append ("<td width='40%'>" + lview.getCurrentProcess() + "</td>\n");
	        buf.append ("<td width='20%'><b>Date Code</b></td>\n");
	        buf.append ("<td width='20%'>" + lview.getDateCode() + "</td>\n");
	        buf.append ("</tr><tr><td width='20%'><b>Vendor & Location</b></td>\n");
	        buf.append ("<td width='40%'>" + lview.getVendorLocationName() + "</td>\n");
	        buf.append ("<td width='20%'><b>Status</b></td>\n");
	        buf.append ("<td width='20%'>" + lview.getStatus() + "</td>\n");
	        buf.append ("</tr><tr><td width='20%'><b>Date In</b></td>\n");
	        buf.append ("<td width='40%'>" + lview.getDateIn() + "</td>\n");
	        buf.append ("<td width='20%'><b>Quantity In</b></td>\n");
	        buf.append ("<td width='20%'>" + lview.getQuantityIn() + "</td>\n");
	        buf.append ("</tr><tr><td width='20%'><b>Date Out</b></td>\n");
	        buf.append ("<td width='40%'>" + lview.getDateOut() + "</td>\n");
	        buf.append ("<td width='20%'><b>Quantity Out</b></td>\n");
	        buf.append ("<td width='20%'>" + lview.getQuantityOut() + "</td>\n");
	        buf.append ("</tr><tr><td width='20%'><b>Current Yield</b></td>\n");
	        buf.append ("<td width='40%'>" + lview.getCurrentYield() + "</td>\n");
	        buf.append ("<td width='20%'>&nbsp;</td>\n");
		    buf.append ("<td width='20%'>&nbsp;</td>\n");
	        buf.append ("</tr><tr><td colspan='4'>&nbsp;</td></tr>\n");
		    buf.append ("<tr><td width='20%'><b>Split Lot Number </b></td>\n");
	        buf.append ("<td width='40%'>" + splitLotNumber + "</td>\n");
	        buf.append ("<td width='20%'><b>Split Lot Quantity </b></td>\n");
		    buf.append ("<td width='20%'>" + quantity + "</td>\n");
	        buf.append ("</tr></table>\n");

	        return buf.toString();
    }
}
